package cn.wit.summit.chwan.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.CommentAllListFragmentAdapter;
import cn.wit.summit.chwan.models.dto.CommentAlllistIntentData;
import cn.wit.summit.chwan.models.dto.CommentBaseBean;
import cn.wit.summit.chwan.models.event.DeleteOrModifyCommentEvent;
import cn.wit.summit.chwan.models.request.AddPraiseRequest;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.request.GetGameCommentRequest;
import cn.wit.summit.chwan.models.response.AddPraiseResponse;
import cn.wit.summit.chwan.models.response.CommentAllListResponse;
import cn.wit.summit.chwan.models.response.GetCommentTokenResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.CommentCreatActivity;
import cn.wit.summit.chwan.ui.activity.CommentDetailActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringToUnicodeUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.HistogramView;
import cn.wit.summit.chwan.widgets.LoadMoreRecyclerView;
import cn.wit.summit.chwan.widgets.MStarBar;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/4/22.
 */

public class CommentAllListFragment extends BaseFragment implements CommentAllListFragmentAdapter.Listener {

//    @Bind(R.id.commentAllList)
    LoadMoreRecyclerView commentAllList;

    private String commentId;
    private String commentContent;
    private float commentStars;
    private String gameId;
    private String packageName;
    private String commentScoreSwitch;//星星开关 1：开，0：关
    private int bespeakSwitch;//是否是预约游戏 1：开，0：关
    private int sgcSwitch;//游戏启动次数 1：开，0：关
    private String gameType;
    private int gameIsStart;

    private View headView;
    private LinearLayout start_ll;
    private LinearLayout point_ll;
    private LinearLayout goCommit;
    private MStarBar commentHeadMstarBar;
    private TextView editText5;
    private TextView comment_head_nopoint_tx;
    private TextView commentHeadPointTx;
    private TextView commentHeadNumTx;
    private HistogramView oneHv, twoHv, threeHv, fourHv, fiveHv;

    private CommentAllListFragmentAdapter mAdapter;
    private List<CommentAllListFragmentAdapter.ViewBean> dataSet = new ArrayList<>();

    private Context mContext;
    private int pn = 1;
    private int pc = 10;

    private String comentToken = "-1";
    private int uId;
    private String uToken;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LogUtils.e("intentFragment oncretview");
        View view=inflater.inflate(R.layout.activity_comment_all_list,container,false);
//        ButterKnife.bind(this,view);
        commentAllList=view.findViewById(R.id.commentAllList);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);//订阅
        }

        if (retrofitManager==null) {
            retrofitManager = RetrofitManager.getInstance(getActivity());
            retrofit = retrofitManager.getCommentRetrofit();
            api = retrofit.create(ApiUtil.class);
        }

        mContext=getContext();
        initData();
        initView();
        initListView();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);//订阅
        }
        if (AccountUtil.getInstance().getAccountData()!=null) {
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            if (mAdapter!=null) {
                mAdapter.setUid(uId);
            }
        }

        pn = 1;
        getData();
    }

    private void initData() {
        Bundle intent =getArguments();
        CommentAlllistIntentData intentData= (CommentAlllistIntentData) intent.getSerializable("data");
        commentId = intentData.getCommentId();
        commentContent = intentData.getCommentContent();
        gameId = intentData.getGameId();
        gameType = intentData.getGameType();
        packageName = intentData.getPackageName();
        commentScoreSwitch = intentData.getCommentScoreSwitch();
        commentStars = intentData.getCommentStars();
        gameIsStart = intentData.getGameIsStart();
        bespeakSwitch = intentData.getBespeakSwitch();
        sgcSwitch =intentData.getSgcSwitch();

        if (AccountUtil.getInstance().getAccountData()!=null) {
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
        }
    }

    private void initView() {
        headView = LayoutInflater.from(mContext).inflate(R.layout.comment_list_head_view, null);
        oneHv = (HistogramView) headView.findViewById(R.id.oneHv);//#F47500
        twoHv = (HistogramView) headView.findViewById(R.id.twoHv);//#F47500
        threeHv = (HistogramView) headView.findViewById(R.id.threeHv);//#F47500
        fourHv = (HistogramView) headView.findViewById(R.id.fourHv);//#F47500
        fiveHv = (HistogramView) headView.findViewById(R.id.fiveHv);//#F47500
        commentHeadMstarBar = (MStarBar) headView.findViewById(R.id.comment_head_mstarBar);
        commentHeadPointTx = (TextView) headView.findViewById(R.id.comment_head_point_tx);
        comment_head_nopoint_tx = (TextView) headView.findViewById(R.id.comment_head_nopoint_tx);
        commentHeadNumTx = (TextView) headView.findViewById(R.id.comment_head_num_tx);
        editText5 = (TextView) headView.findViewById(R.id.editText5);
        editText5.setText("玩过");
        start_ll = (LinearLayout) headView.findViewById(R.id.start_ll);
        point_ll = (LinearLayout) headView.findViewById(R.id.point_ll);
        headView.findViewById(R.id.goCommit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textTopRight();
            }
        });
        commentHeadMstarBar.setIntegerMark(false);
        commentHeadMstarBar.setEnabled(false);
    }

    private void initListView() {
        mAdapter = new CommentAllListFragmentAdapter(mContext, uId, dataSet, this);
        commentAllList.setLayoutManager(new LinearLayoutManager(getContext()));
        commentAllList.setAdapter(mAdapter);
        commentAllList.setVerticalScrollBarEnabled(false);
        commentAllList.setAutoLoadMoreEnable(true);
        commentAllList.setVisibility(View.VISIBLE);
        commentAllList.setLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                getData();
            }
        });

//        getData();
    }

    private void getData() {
        comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
        if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
            getCommentToken(null, 0, 0, 3);
            return;
        }
        uId = AccountUtil.getInstance().getUid();
        uToken = AccountUtil.getInstance().getToken();

        GetGameCommentRequest commentRequest = retrofitManager.getGameCommentsRequest(comentToken, gameId, uId, pn, pc);
        api.getGameComments(commentRequest).enqueue(new MyCallback<ResponseBase<CommentAllListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<CommentAllListResponse> model) {
                showMain(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
                commentAllList.notifyMoreFinish(true);
            }
        });
    }

    private void showMain(CommentAllListResponse commentBeans) {
        if (commentBeans==null) {
            if (pn==1) {
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.EMPTY, null);
                dataSet.add(viewBean);
                mAdapter.notifyDataSetChanged();
            }
            commentAllList.notifyMoreFinish(true);
            return;
        }
        if (pn == 1) {
            dataSet.clear();
        }

        List<CommentBaseBean> commentBaseBeans = new ArrayList<>();

        List<CommentBaseBean> hotComment = commentBeans.getHot_comment();
        if (hotComment!=null && hotComment.size()>0) {
            CommentBaseBean bean = new CommentBaseBean();
            bean.setIs_hot(1);
            bean.setTitle(true);
            bean.setPn(pn);
            commentBaseBeans.add(bean);
            commentBaseBeans.addAll(hotComment);
        }

        CommentBaseBean selfComment = commentBeans.getSelf_comment();
        List<CommentBaseBean> generalComment = commentBeans.getGeneral_comment();
        if (selfComment != null && pn == 1) {
            CommentBaseBean bean = new CommentBaseBean();
            bean.setIs_hot(2);
            bean.setTitle(true);
            bean.setPn(pn);
            commentBaseBeans.add(bean);
            selfComment.setPn(pn);
            commentBaseBeans.add(selfComment);
        }

        if (generalComment != null && generalComment.size() > 0) {
            if (pn == 1 && selfComment == null) {
                CommentBaseBean bean = new CommentBaseBean();
                bean.setIs_hot(2);
                bean.setTitle(true);
                bean.setPn(pn);
                commentBaseBeans.add(bean);
            }
            for (int i=0;i<generalComment.size();i++) {
                CommentBaseBean temp = generalComment.get(i);
                temp.setPn(pn);
                commentBaseBeans.add(temp);
            }
        }

        addViewItem(commentBaseBeans);

        if (commentBaseBeans.size()<pc) {
            if (pn==1 && commentBaseBeans.size()==0) {
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.EMPTY, null);
                dataSet.add(viewBean);
                mAdapter.notifyDataSetChanged();
            }
            //没有更多
            commentAllList.notifyMoreFinish(false);
        } else {
            pn++;
            commentAllList.notifyMoreFinish(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    private void addViewItem(List<CommentBaseBean> list) {
        for (int i = 0; null != list && i < list.size(); i++) {
            CommentBaseBean bean = list.get(i);
            if (bean.isTitle()) {
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.TITLE, new CommentAllListFragmentAdapter.ViewBean.Comment(bean));
                dataSet.add(viewBean);
            } else {
                String str = bean.getContent();
                if (str.contains("EM-")){
                    try {
                        str = StringToUnicodeUtil.unicode2String(str);
                        bean.setContent(str);
                    } catch (Exception e) {
                        LogUtils.e("---m---e.getMessage():"+e.getMessage());
                    }
                }
                CommentAllListFragmentAdapter.ViewBean viewBean = new CommentAllListFragmentAdapter.ViewBean(CommentAllListFragmentAdapter.ViewType.COMMENT, new CommentAllListFragmentAdapter.ViewBean.Comment(bean));
                dataSet.add(viewBean);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    private void textTopRight() {
        //是否登陆
        if(AccountUtil.getInstance().getUid()==0) {
            IntentUtil.getInstance().goLoginActivity(getActivity());
            return;
        }

        Intent intent = new Intent(mContext, CommentCreatActivity.class);
        intent.putExtra("gameId", gameId);
        intent.putExtra("packageName", packageName);
        intent.putExtra("commentScoreSwitch", commentScoreSwitch);
        intent.putExtra("bespeakSwitch", bespeakSwitch);
        intent.putExtra("gameType", gameType);
        intent.putExtra("gameIsStart", gameIsStart);

        //判断有没有自己的评论
//                if (mAdapter.getMyCommentPosition()==-1 || mySelf==null) {
//                } else {
//                    intent.putExtra("commentId", );
//                    intent.putExtra("commentContent", );
//                    intent.putExtra("commentStars", );
//                }

        startActivity(intent);
    }

    public static CommentAllListFragment newInstance(CommentAlllistIntentData intentData) {
        LogUtils.e("intentFragment newinstance");
        Bundle args = new Bundle();
        args.putSerializable("data", intentData);
        CommentAllListFragment fragment = new CommentAllListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 1);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.addPraiseRequest(comentToken, gameId, uId, uToken, commentId, type, pn);
            api.addPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 1);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code==801)
                        getCommentToken(bean, position, type, 1);
                    resultShow(msg, true, position, 1);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 1);
        }
    }

    @Override
    public void onUnPraise(final CommentBaseBean bean, final int position, final int type) {
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            comentToken = PreferenceUtil.getPreferences(mContext, PreferenceUtil.PRE_COMMENT_TOKEN);
            if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
                getCommentToken(bean, position, type, 2);
                return;
            }
            uId = AccountUtil.getInstance().getUid();
            uToken = AccountUtil.getInstance().getToken();
            commentId = bean.getId();

            AddPraiseRequest tempRequest = retrofitManager.unPraiseRequest(comentToken, gameId, uId, uToken, commentId, type, pn);
            api.subPraise(tempRequest).enqueue(new MyCallback<ResponseBase<AddPraiseResponse>>() {
                @Override
                public void onSuccess(ResponseBase<AddPraiseResponse> model) {
                    checkReset(position, 2);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (code==801)
                        getCommentToken(bean, position, type, 2);
                    resultShow(msg, true, position, 2);
                }
            });
        } else {
            resultShow("网络连接失败，再试试吧~", true, position, 2);
        }
    }

    @Override
    public void onRootView(CommentBaseBean bean, int position) {
//        CommentDetailActivity_.intent(context).gameId(bean.getGame_id()).commentId(bean.getId())
//                .gameType(gameType).bespeakSwitch(bespeakSwitch)
//                .gameIsStart(gameIsStart).sgcSwitch(sgcSwitch)
//                .packageName(packageName).commentScoreSwitch(commentScoreSwitch).start();

        Intent intent = new Intent(getActivity(), CommentDetailActivity.class);
        intent.putExtra("commentId", bean.getId());
        intent.putExtra("data", bean);
        getActivity().startActivity(intent);
    }

    @Override
    public void onClickHead() {

    }

    public void checkReset(int position, int i) {
        if (i==1) {
            mAdapter.resetDespise(position, 1);
        } else {
            mAdapter.resetPraise(position, 1);
        }
//        commentAllList.notifyMoreFinish(true);
    }

    private void resultShow(String msg, boolean b, int position, int type) {
        showToast(msg);
        if (b) {
            if (type==1)
                mAdapter.resetPraise(position, 0);
            else
                mAdapter.resetDespise(position, 0);
        }
    }

    private void getCommentToken(final CommentBaseBean bean, final int position, final int type, final int i) {
        GetCommentTokenRequest tempRequest = retrofitManager.getCommentTokenRequest();
        api.getCommentToken(tempRequest).enqueue(new MyCallback<ResponseBase<GetCommentTokenResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GetCommentTokenResponse> model) {
                GetCommentTokenResponse data = model.getData_info();
                String token = AESUtils.encrypt4Comment(data.getToken() + "|" + data.getTimes());
                comentToken = token;
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, token);
                PreferenceUtil.saveLongPreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN_TIME, data.getTimes());
                if (i==1)
                    onPraise(bean, position, type);
                else if (i==2)
                    onUnPraise(bean, position, type);
                else if (i==3)
                    getData();
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(mContext, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                showToast(msg);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeComment(DeleteOrModifyCommentEvent event) {
        pn = 1;
        getData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//订阅
    }
}
